#!/usr/bin/env python
"""
-->
CSVFileInfo = "Defines which csv-files you like to work with."
FilePath = {'type': "System.String", 'description': "Path of the csv file you like to work with.", 'validation': "IsFile"}
Seperator = {'type': "System.String", 'description': "The delimiter which split the data. In most cases comma or semicolon.", 'defaultValue': ";"}
HasHeader = {'type': "System.Boolean", 'description': If true the csv-file should contain header-informations.", 'defaultValue': "true"}
-->

<--
CSVData = "Defines the data, which this plugins loads from the given csv-files."
<--
"""

#http://openbook.galileocomputing.de/python/python_kapitel_19_005.htm#mj068051f9093b3bd5bfc5628714320a14	

from MyClever.Lib import MissionPlugin
import csv

__author__ = "Mathias Mielitz"
__copyright__ = "Copyright 2012, MyCleverFriend"
__credits__ = ["Mathias Mielitz"]
__license__ = "GPL"
__version__ = "1.0.0.0"
__maintainer__ = "Mathias Mielitz"
__email__ = "m.mielitz@adrabbit.de"
__status__ = "Production"
__description__ = "Parse every given CSV files."

class ReadCSV(MissionPlugin):
	def Work(self):

		csvInfoPackage = self.GetDataReader("CSVFileInfo")
		while csvInfoPackage.Read():
			self.AddNewLoggingMessage("CSVFileInfo", "read csv-file: " + csvInfoPackage["FilePath"].ToString());			

			reader = csv.reader(open(csvInfoPackage["FilePath"].ToString(), "rb"), delimiter=csvInfoPackage["Seperator"].ToString()) 
			
			# define column Header names
			fieldHeaders = [];

			firstRow = reader.next();

			for columnID in range(len(firstRow)):
				columnName = "Column{0}".format(columnID);
				if ("true" == csvInfoPackage["HasHeader"].ToString().lower()):
					columnName = firstRow[columnID];
				fieldHeaders.append((columnName,"System.String"));

			self.CreateNewSchemaForPackage("CSVData", fieldHeaders);

			for row in reader:
				newRow = self.CreateNewRowFromPackage("CSVData");
				
				for columnID in range(len(fieldHeaders)):
					newRow[fieldHeaders[columnID][0]] = row[columnID];
					columnID = columnID + 1;

				self.AddNewRowToPackage("CSVData", newRow);